package nsu.edu.zsq.service.impl.sys;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import nsu.edu.zsq.bean.SysUser;
import nsu.edu.zsq.common.RequestHolder;
import nsu.edu.zsq.dao.SysUserMapper;
import nsu.edu.zsq.exception.ParamException;
import nsu.edu.zsq.service.sys.SysLogService;
import nsu.edu.zsq.service.sys.SysUserService;
import nsu.edu.zsq.util.PasswordUtil;

/** 
* Description: 管理员用户信息的service实现类<br>
*/
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysLogService sysLogService;
    
    @Override
    public SysUser getSysUser() {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(RequestHolder.getCurrentSysUser().getId());
        return sysUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePasswordByPrimaryKey(SysUser sysUser) {
        // 对新密码进行数据校验
        String password = sysUser.getPassword();
        String regEx = "^[\\S]{6,12}$";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(password);
        if (!matcher.matches()) {
            throw new ParamException("密码必须6到12位，且不能出现空格");
        }
        // md5加密
        sysUser.setPassword(PasswordUtil.md5(sysUser.getPassword()));
        sysUser.setOperator(RequestHolder.getCurrentSysUser().getAccount());
        sysUser.setOperatorTime(new Date());
        SysUser before = getSysUser();
        // 修改用户信息
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
        
		/*
		 * // 添加日志 SysUser after = new SysUser(); // 对象拷贝
		 * BeanUtils.copyProperties(before, after);
		 * after.setPassword(sysUser.getPassword());
		 * after.setOperator(sysUser.getOperator());
		 * after.setOperatorTime(sysUser.getOperatorTime()); String instruction =
		 * "个人信息-修改密码"; sysLogService.saveSysLogBySysUser(before, after, instruction);
		 */
    }

}
